package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.bean.UploadFile;
import com.fwtai.bean.UploadObject;
import com.fwtai.config.ConfigFile;
import com.fwtai.config.LocalUserId;
import com.fwtai.service.AsyncService;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolString;
import com.fwtai.web.KnowledgeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 知识业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2021-07-23 11:23:29
 * @官网 <url>http://www.fwtai.com</url>
 */
@Service
public class KnowledgeService{

  @Value("${upload_dir_window}")
  private String dir_window;

  @Value("${upload_dir_linux}")
  private String dir_linux;

  @Autowired
  private AsyncService asyncService;

  @Resource
  private KnowledgeDao knowledgeDao;

  public String add(final HttpServletRequest request){
    final PageFormData formData = new PageFormData(request);
    final String p_details = "details";
    final String p_cover_original = "cover_original";
    final String p_domain_id = "domain_id";
    final String p_title = "title";
    final String validate = ToolClient.validateField(formData,p_details,p_domain_id,p_title,p_cover_original);
    if(validate != null)return validate;
    if(formData.getString("details").length() > 102400000){
      return ToolClient.createJsonFail("内容详情字数太长");
    }
    if(formData.getString(p_domain_id) != null){
      final Long value = formData.getLong(p_domain_id);
      if(value == null){
        return ToolClient.createJsonFail("类型领域有误");
      }
    }
    if(formData.getString("title").length() > 100){
      return ToolClient.createJsonFail("标题字数太长");
    }
    final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
    final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/knowledge/cover",false,1,3,true);
    final String errorMsg = uploadObject.getErrorMsg();
    if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
    final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
    if(listFiles == null || listFiles.size() <= 0) return ToolClient.createJsonFail("请选择上传文件");
    final UploadFile uploadFile = listFiles.get(0);
    final String urlFile = uploadFile.getUrlFile();
    final String fullPath = uploadFile.getFullPath();
    formData.put("cover",urlFile);
    formData.put("path",fullPath);
    /*处理缩略图final String fileName = uploadFile.getFileName();
    final String dir_original = fullPath.substring(0,fileName.length()-1)+"thumbnail/";
    final File file = new File(dir_original);
    if(!file.exists()){
       file.mkdir();
    }
    final String cover_middle = dir_original+fileName;
    ToolImage.compress(fullPath,cover_middle);
    formData.put("cover_middle",cover_middle);*/
    formData.put("user_id",LocalUserId.get());
    formData.put("kid",new IdBuilder().getId121L());
    return ToolClient.executeRows(knowledgeDao.add(formData));
  }

  public String edit(final HttpServletRequest request){
    final PageFormData formData = new PageFormData(request);
    final String p_kid = "kid";
    final String p_details = "details";
    final String p_domain_id = "domain_id";
    final String p_title = "title";
    final String validate = ToolClient.validateField(formData,p_details,p_domain_id,p_title,p_kid);
    if(validate != null)return validate;
    if(formData.getString("details").length() > 102400000){
      return ToolClient.createJsonFail("内容详情字数太长");
    }
    if(formData.getString(p_domain_id) != null){
      final Long value = formData.getLong(p_domain_id);
      if(value == null){
        return ToolClient.createJsonFail("类型领域有误");
      }
    }
    if(formData.getString("title").length() > 100){
      return ToolClient.createJsonFail("标题字数太长");
    }
    final String baseDir = ToolString.isLinuxOS() ? dir_linux : dir_window;
    final UploadObject uploadObject = ToolClient.uploadFile(request,baseDir,"/knowledge/cover",false,1,3,false);
    final String errorMsg = uploadObject.getErrorMsg();
    if(errorMsg != null) return ToolClient.createJsonFail(errorMsg);
    final ArrayList<UploadFile> listFiles = uploadObject.getListFiles();
    final String kid = formData.getString(p_kid);
    String coverPath = null;
    if(listFiles != null && listFiles.size() > 0){
      final UploadFile uploadFile = listFiles.get(0);
      final String fullPath = uploadFile.getFullPath();
      formData.put("cover",uploadFile.getUrlFile());
      formData.put("path",fullPath);
      /*处理缩略图final String fileName = uploadFile.getFileName();
      final String dir_original = fullPath.substring(0,fileName.length()-1)+"thumbnail/";
      final File file = new File(dir_original);
      if(!file.exists()){
          file.mkdir();
      }
      final String cover_middle = dir_original+fileName;
      ToolImage.compress(fullPath,cover_middle);
      formData.put("cover_middle",cover_middle);*/
      coverPath = knowledgeDao.getCoverPath(kid);
    }
    final String exist_key = knowledgeDao.queryExistById(kid);
    if(exist_key == null){
      return ToolClient.createJsonFail("数据不存在,刷新重试");
    }
    final String loginId = LocalUserId.get();
    if(!ConfigFile.SUPER_KEY.equals(loginId)){
      formData.put("loginId",loginId);
    }
    final int rows = knowledgeDao.edit(formData);
    if(rows > 0 && coverPath != null)
      asyncService.delKnowledgeCover(coverPath);
    return ToolClient.executeRows(rows,"操作成功","编辑失败");
  }

  public String queryById(final PageFormData formData){
    final String p_id = "id";
    final String validate = ToolClient.validateField(formData,p_id);
    if(validate != null)return validate;
    return ToolClient.queryJson(knowledgeDao.queryById(formData.getString(p_id)));
  }

  public String delById(final PageFormData formData){
    final String p_kid = "id";
    final String validate = ToolClient.validateField(formData,p_kid);
    if(validate != null)return validate;
    final String kid = formData.getString(p_kid);
    final String exist_key = knowledgeDao.queryExistById(kid);
    if(exist_key == null){
      return ToolClient.createJsonFail("删除失败,数据已不存在");
    }
    final String coverPath = knowledgeDao.getCoverPath(kid);
    final String loginId = LocalUserId.get();
    if(!ConfigFile.SUPER_KEY.equals(loginId)){
      formData.put("loginId",loginId);
    }
    final int rows = knowledgeDao.delById(formData);
    if(rows > 0){
      asyncService.delKnowledgeCover(coverPath);
    }
    return ToolClient.executeRows(rows,"操作成功","删除失败,请勿删除他人的内容");
  }

  public String delByKeys(final PageFormData formData){
    final String p_ids = "ids";
    final String validate = ToolClient.validateField(formData,p_ids);
    if(validate != null)return validate;
    final String ids = formData.getStringRemove(p_ids);
    final long[] lists = ToolString.keysToArarry(ids);
    if(lists == null){
      return ToolClient.createJsonFail("请选择要删除的数据");
    }
    formData.put("lists",lists);
    final String loginId = LocalUserId.get();
    if(!ConfigFile.SUPER_KEY.equals(loginId)){
      formData.put("loginId",loginId);
    }
    return ToolClient.executeRows(knowledgeDao.delByKeys(formData),"操作成功","数据不存在,刷新重试");
  }

  public String listData(PageFormData formData){
    try {
      formData = ToolClient.dataTableMysql(formData);
      if(formData == null)return ToolClient.jsonValidateField();
      final String loginId = LocalUserId.get();
      if(!ConfigFile.SUPER_KEY.equals(loginId)){
        formData.put("loginId",loginId);
      }
      final HashMap<String,Object> map = knowledgeDao.listData(formData);
      return ToolClient.dataTableOK((List<Object>)map.get(ConfigFile.rows),map.get(ConfigFile.total));
    } catch (Exception e){
      return ToolClient.dataTableException(formData.get("sEcho"));
    }
  }

  public String getDomainList(){
    return ToolClient.queryJson(knowledgeDao.getDomainList());
  }

  public String getPreInfo(final String kid){
    if(kid == null || kid.length() <=0){
      return ToolClient.jsonValidateField();
    }
    return ToolClient.queryJson(knowledgeDao.getPreInfo(kid));
  }
}